from django_redis import get_redis_connection
from utils.hmjson import dumps, loads


def merge_cookie2redis(request, response, user_id):
    '''

    :param request:读取cookie中的数据
    :param response: 合并完成后删除购物车中的数据
    :param user_id:
    :return: 返回response

    '''
    # 读取cookie
    cart = request.COOKIES.get('cart')
    if not cart:
        return response
    cart_dict = loads(cart)

    # 写redis
    redis_cli = get_redis_connection('cart')
    for sku_id, item in cart_dict.items():
        # 将数量保存到哈希中
        redis_cli.hset('cart%d' % user_id, sku_id, item.get('count'))
        # 讲选中的状态放到set中，选中添加，为选中则不添加
        if item.get('selected'):
            redis_cli.sadd('cart_selected%d' % user_id, sku_id)

    # 删除cookie
    response.delete_cookie('cart')

    # 返回
    return response
